component extends="Controller" output="false" {

	public void function init(){
	}  

	public void function index(){
	}

	/*
		Step 1 - select the fixture we are playing
			this screen should show the two teams playing
	*/
	public void function selectFixture(){
		//fixtures = model("Fixture").findAll(
			//select='fixtures.round_no,clubs.name',include='homeClub,awayClub');
		fixtures = model("Fixture").getAllFixturesWithClubs();		
	}  

	public void function autoSelectTeam() {
		// Auto grab a team
		team = model("Team").findOne();
		redirectTo(route="teamSelection",fixtureid=params.fixtureid, teamid=team.id);
	}

	public void function teamSelection() {
		team = model("Team").findByKey(key=params.teamid,include="team_players");		
		teamQry = model("Team").getTeamPlayersWithPlayerNames(params.teamid);
		players = model("Player").getPlayersByFixtureId(params.fixtureid);
	}

	public void function selectPlayer() {
		players = model("Player").getPlayersByFixtureId(params.fixtureid);
	}

	public void function saveTeamPlayers() {
		team = model("Team").findByKey(params.team.id);
    	if(team.update(params.team)){
    		flashInsert(success="Updated");
    		redirectTo(route="teamSelection", fixtureid=params.fixtureid, teamid=params.team.id);
    	}
	}

	public void function doSelectTeamPlayer() {
		// pretty sure we need to add fixtureid to team

		team = model("Team").findByKey(key=params.teamid);
	}

	// Dashboard screen after team is finalised 
	public void function teamDashboard() {

	}

	/*


http://www.afl.com.au/api/cfs/afl/playerRatings?roundId=CD_R201401413&teamId=CD_T20&pageSize=40&pageNum=1
http://www.afl.com.au/api/cfs/afl/season?seasonId=CD_S2014014
http://www.afl.com.au/api/cfs/afl/seasons -- doesnt wrok with regular way
http://www.afl.com.au/api/cfs/afl/statsCentre/teams?competitionId=CD_S2014014
http://www.afl.com.au/api/cfs/afl/statsCentre/players?competitionId=CD_S2014014
http://www.afl.com.au/api/cfs/afl/ladder/CD_S2014014


http://www.afl.com.au/api/vgn-ext-templating/content-services/seasons/fmr
http://www.afl.com.au/api/vgn-ext-templating/content-services/season/CD_S2014014/rounds/
http://www.afl.com.au/api/vgn-ext-templating/content-services/round/CD_R201401414/matches/

http://www.afl.com.au/api/cfs/afl/matchItem/CD_M20140141301
http://www.afl.com.au/api/cfs/afl/matchScore/full/CD_M20140141301
http://www.afl.com.au/api/cfs/afl/matchItems/round/CD_R201401413 -- gets all the matches for the round
http://www.afl.com.au/api/cfs/afl/matchCentre/CD_M20140141301/scoreWorm
http://www.afl.com.au/api/cfs/afl/matchCentre/CD_M20140141301/playerStats
http://www.afl.com.au/api/cfs/commentaryFeed/CD_M20140141301
http://www.afl.com.au/api/cfs/afl/matchCentre/CD_M20140141301/teamStats

http://www.afl.com.au/api/gas/afl/roundVideo/CD_R201401411
http://api.afl.com.au/cfs/afl/video?categories=Access%20All%20Areas
http://api.afl.com.au/cfs/afl/video?categories=Media%20Conferences
http://api.afl.com.au/cfs/afl/video?categories=News

http://www.collingwoodfc.com.au/api/cfs/afl/statsCentre/players?competitionId=CD_S2014014&teamIds=CD_T40
http://www.collingwoodfc.com.au/api/cfs/afl/statsCentre/players?competitionId=CD_S2014014&roundId=CD_R201401401&teamIds=CD_T40
	*/

	/*
	@hint 	Very simply gets a token and sets it to session scope to re-use for other requests
	*/
	public function _getToken() {
		if(NOT StructKeyExists(session,'token'))
		{
			var requestUrl = "http://www.afl.com.au/api/cfs/afl/WMCTok";		 
			var http = new http();
			http.setMethod("post");
			http.setURL("#requestUrl#");
			http.addParam(type="formfield",name="a",value="1"); 
			result = deserializeJSON(http.send().getPrefix().FileContent);
			if(StructKeyExists(result,'token'))
			{
				session.token = result.token;
			}	
		}
	}

	

	public function doTestRequest() {
		_getToken();

		var currentRoundId = 0;
		var roundPhase = '';
		var arrRounds = ArrayNew(1);
		var arrRoundIds = ArrayNew(1);
		var http = new http();
		http.setMethod("get");
		http.setUrl("http://www.collingwoodfc.com.au/api/cfs/afl/statsCentre/players?competitionId=CD_S2014014&roundId=CD_R201401401&teamIds=CD_T40");
		http.addParam(type="header", name="X-media-mis-token", value="#session.token#");
		http.setTimeout(120);
		result = deserializeJSON(http.send().getPrefix().FileContent);
		writeDump(result);
		abort;
		//renderNothing();
	}	

	/*
	@hint 	Gets all the rounds based on a season, includes the current round and the 
			status of the current round which can be either
			TEAMS_ANNOUNCED or tbc
	*/
	public function getRoundData() {
		_getToken();

		var currentRoundId = 0;
		var roundPhase = '';
		var arrRounds = ArrayNew(1);
		var arrRoundIds = ArrayNew(1);
		var http = new http();
		http.setMethod("get");
		http.setUrl("http://www.afl.com.au/api/cfs/afl/season?seasonId=CD_S2014014");
		http.addParam(type="header", name="X-media-mis-token", value="#session.token#");
		result = deserializeJSON(http.send().getPrefix().FileContent);
		
		if(StructKeyExists(result,'season')){
			if(StructKeyExists(result.season,'competitons'))
			{
				if(ArrayLen(result.season.competitions) eq 1)
				{
					if(StructKeyExists(result.season.competitions[1],'currentRoundId'))
					{
						currentRoundId = result.season.competitions[1].currentRoundId;
					}
					if(StructKeyExists(result.season.competitions[1],'roundPhase'))
					{
						roundPhase = result.season.competitions[1].roundPhase;
					}
					// Retrieve all the rounds data
					/*
					if(StructKeyExists(result.season.competitions[1],'rounds'))
					{
						arrRounds = result.season.competitions[1].rounds;
						for(roundData in arrRounds) {
						   if(StructKeyExists(roundData,'roundId'))
						   {
						   		arrayAppend(arrRoundIds,roundData.roundId);
						   }
						}
					}
					*/
				}
			}
		}
		writeDump(result);
		renderNothing();
	}

	/* IMPORT STUFF */
	public function doAFLImport() {
		// Make sure the token exists already
		_getToken();

		var http = new http();
		http.setMethod("get");
		// CD_M20140141301 = CD_20140[year][round][match]
		
		http.setUrl("http://www.afl.com.au/api/cfs/afl/matchCentre/CD_M20140141301/playerStats");
		http.addParam(type="header", name="X-media-mis-token", value="#session.token#");
		result = deserializeJSON(http.send().getPrefix().FileContent);

		origin_clubId = '';
		if(StructKeyExists(result,'awayTeam'))
		{
			if(StructKeyExists(result.awayTeam,'team'))
			{
				origin_clubId = result.awayTeam.team.teamId;
			}
			// Get the player stats only if the origin club id is set
			if(StructKeyExists(result.awayTeam,'playerStats') AND Len(origin_clubId))
			{
				sqlData = {};          
          		for(playerIdx in result.awayTeam.playerStats) {
					// Player info
		            if(StructKeyExists(playerIdx,'player'))
		            {
		            	sqlData['origin_playerId'] = playerIdx.player.playerId;
		            }
					// Player stats
					if(StructKeyExists(playerIdx,'stats'))
					{
						if(StructKeyExists(playerIdx.stats,'dreamTeamPoints'))
						{
							sqlData['cur_fantasy_points'] = playerIdx.stats.dreamTeamPoints;
						}
						/*
						if(StructKeyExists(playerIdx.stats,'averages'))
						{
							if(StructKeyExists(playerIdx.stats.averages,'dreamTeamPoints'))
							{
								sqlData['avg_fantasy_points'] = playerIdx.stats.averages.dreamTeamPoints;	
							}
							if(StructKeyExists(playerIdx.stats.totals,'dreamTeamPoints'))
							{
								sqlData['cur_fantasy_points'] = playerIdx.stats.totals.dreamTeamPoints;
							}	
						}
						*/	
					}
				}
			}
		}
		if(StructKeyExists(result,'homeTeam'))
		{
			
		}
		writeDump(result);
		abort;
	}
}